package io.github.thundzeng.miniemail;

import com.sun.mail.util.MailSSLSocketFactory;

import jakarta.activation.DataHandler;
import jakarta.activation.FileDataSource;
import jakarta.mail.BodyPart;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import jakarta.mail.internet.MimeUtility;
import java.util.stream.Stream;
import jakarta.activation.DataSource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;

/**
 * 邮件发送器
 *
 * @version 2.0
 */
public class MailSender {

    /**
     * 邮件发送地址
     */
    private String FROM = "luzx-ici@inspurworld.com";
    /**
     * 邮件发送人名
     */
    private String FROM_NAME = "lzx";
    /**
     * 授权码
     */
    private String PASSWORD = "yF8OGhj5GTsIJ6xj";
    /**
     * 邮件发送人
     */
    private String[] TO = new String[]
        {"axiao0514@126.com", "liaoyk-ici@inspurworld.com","rian1986_1021@163.com",
            "wangchl05@inspur.com","luzx-ici@inspurworld.com","233122298@qq.com"};;
    /**
     * 邮件抄送人
     */
    private String[] CC;
    /**
     * 邮件密送人
     */
    private String[] BCC;
    /**
     * 邮件smtp协议host地址
     */
    private String HOST;

    /**
     * 是否开启SSL认证，QQ邮箱自动检测开启
     */
    private boolean isSSLAuth = true;

    /**
     * 是否输出debug,默认开启
     */
    private boolean isDebug = true;

//    public void setDebug(boolean isDebug){
//        this.isDebug = isDebug;
//    }
//
//    public void setSSLAuth(boolean SSLAuth) {
//        isSSLAuth = SSLAuth;
//    }
//
//    private MailSender() {
//    }
//
//    /**
//     * 值得注意的是，在new MailSender()对象时并不支持无参构造，也不强制设置抄送人和密送人。
//     * <n>
//     *
//     * @param FROM      发件人地址
//     * @param FROM_NAME 发件人名
//     * @param TO        收件人地址
//     * @param HOST      smtp协议host地址
//     */
//    public MailSender(String FROM, String FROM_NAME, String PASSWORD, String[] TO, String HOST) {
//        this.FROM = FROM;
//        this.FROM_NAME = FROM_NAME;
//        this.PASSWORD = PASSWORD;
//        this.TO = TO;
//        this.HOST = HOST;
//        checkQQMail();
//    }
//
//    /**
//     * 值得注意的是，在new MailSender()对象时并不支持无参构造，也不强制设置抄送人和密送人。
//     * <n>
//     * 更推荐使用public MailSender(String FROM, String FROM_NAME, String PASSWORD, String[] TO, String HOST)方法构造对象，以设置发件人名
//     *
//     * @param FROM     发件人地址
//     * @param PASSWORD 授权码
//     * @param TO       收件人地址
//     * @param HOST     smtp协议host地址
//     */
//    public MailSender(String FROM, String PASSWORD, String[] TO, String HOST) {
//        this.FROM = FROM;
//        this.PASSWORD = PASSWORD;
//        this.TO = TO;
//        this.HOST = HOST;
//        checkQQMail();
//    }
//
//    /**
//     * 设置抄送人
//     *
//     * @param CC 抄送人
//     */
//    public void setCC(String[] CC) {
//        this.CC = CC;
//    }
//
//    /**
//     * 设置密送人
//     *
//     * @param BCC 密送人
//     */
//    public void setBCC(String[] BCC) {
//        this.BCC = BCC;
//    }
//
//    public void sendHtmlMail(String subject, String content)
//        throws GeneralSecurityException, MessagingException, UnsupportedEncodingException, MessagingException {
//        //1.保存配置信息
//        Properties properties = new Properties();
//        properties.put("mail.transport.protocol", "smtp");
//        properties.put("mail.smtp.host", HOST);
//
//        if (isSSLAuth) {
//            //*需要SSL认证的邮箱
//            MailSSLSocketFactory sf = new MailSSLSocketFactory();
//            sf.setTrustAllHosts(true);
//            properties.put("mail.smtp.ssl.enable", "true");
//            properties.put("mail.smtp.ssl.socketFactory", sf);
//        }
//        //2.建立连接
//        Session session = Session.getInstance(properties);
//
//        //输出Debug信息
//        session.setDebug(this.isDebug);
//
//        //3.创建邮件对象
//        MimeMessage message = new MimeMessage(session);
//
//        //设置发件人
//        if ("".equals(FROM_NAME)) {
//            message.setFrom(FROM);
//        } else {
//            message.setFrom(new InternetAddress(FROM, FROM_NAME, "UTF-8"));
//        }
//
//        //设置收件人
//        StringBuilder sbTo = new StringBuilder();
//        for (int i = 0;i< TO.length;i++){
//            if (i== TO.length-1){
//                sbTo.append(TO[i]);
//            }else{
//                sbTo.append(TO[i]).append(",");
//            }
//        }
//        String to = new String(sbTo);
//        InternetAddress[] internetAddressTo = InternetAddress.parse(to);
//        message.setRecipients(MimeMessage.RecipientType.TO,internetAddressTo);
//
//        //设置抄送人
//        if (CC!=null){
//            StringBuilder sbCC = new StringBuilder();
//            for (int i = 0;i< CC.length;i++){
//                if (i== CC.length-1){
//                    sbTo.append(CC[i]);
//                }else{
//                    sbTo.append(CC[i]).append(",");
//                }
//            }
//            String cc = new String(sbCC);
//            InternetAddress[] internetAddressCC = InternetAddress.parse(cc);
//            message.setRecipients(MimeMessage.RecipientType.CC,internetAddressCC);
//        }
//
//        if (BCC!=null){
//            //设置密送人
//            StringBuilder sbBCC = new StringBuilder();
//            for (int i = 0;i< BCC.length;i++){
//                if (i== BCC.length-1){
//                    sbTo.append(BCC[i]);
//                }else{
//                    sbTo.append(BCC[i]).append(",");
//                }
//            }
//            String bcc = new String(sbBCC);
//            InternetAddress[] internetAddressBcc = InternetAddress.parse(bcc);
//            message.setRecipients(MimeMessage.RecipientType.BCC,internetAddressBcc);
//        }
//
//        message.setSubject(subject, "UTF-8");
//        message.setContent(content, "text/html;charset=UTF-8");
//        message.saveChanges();
//
//        //用流传送
//        Transport transport = session.getTransport();
//        transport.connect(FROM, PASSWORD);
//        transport.sendMessage(message, message.getAllRecipients());
//        transport.close();
//    }


    public  String sendHtmlMailWithFiles(String subject, String content, File[] files) throws GeneralSecurityException, MessagingException, UnsupportedEncodingException {
        //1.保存配置信息
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.host", "smtp.qiye.aliyun.com");    //第一步

        if (isSSLAuth) {
            //*需要SSL认证的邮箱
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
        }
        //2.建立连接
        Session session = Session.getInstance(properties);
        //输出Debug信息
        session.setDebug(this.isDebug);

        //3.创建邮件对象
        MimeMessage message = new MimeMessage(session);

        //设置发件人
        if ("".equals(FROM_NAME)) {
            message.setFrom(FROM);
        } else {
            message.setFrom(new InternetAddress(FROM, FROM_NAME, "UTF-8"));
        }

        //设置收件人
        StringBuilder sbTo = new StringBuilder();
        for (int i = 0;i< TO.length;i++){
            if (i== TO.length-1){
                sbTo.append(TO[i]);
            }else{
                sbTo.append(TO[i]).append(",");
            }
        }
        String to = new String(sbTo);
        InternetAddress[] internetAddressTo = InternetAddress.parse(to);
        message.setRecipients(MimeMessage.RecipientType.TO,internetAddressTo);

        //设置抄送人
        if (CC!=null){
            StringBuilder sbCC = new StringBuilder();
            for (int i = 0;i< CC.length;i++){
                if (i== CC.length-1){
                    sbTo.append(CC[i]);
                }else{
                    sbTo.append(CC[i]).append(",");
                }
            }
            String cc = new String(sbCC);
            InternetAddress[] internetAddressCC = InternetAddress.parse(cc);
            message.setRecipients(MimeMessage.RecipientType.CC,internetAddressCC);
        }

        if (BCC!=null){
            //设置密送人
            StringBuilder sbBCC = new StringBuilder();
            for (int i = 0;i< BCC.length;i++){
                if (i== BCC.length-1){
                    sbTo.append(BCC[i]);
                }else{
                    sbTo.append(BCC[i]).append(",");
                }
            }
            String bcc = new String(sbBCC);
            InternetAddress[] internetAddressBcc = InternetAddress.parse(bcc);
            message.setRecipients(MimeMessage.RecipientType.BCC,internetAddressBcc);
        }
        message.setSubject(subject, "UTF-8");
        Multipart multipart = new MimeMultipart();
        //邮件正文
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(content, "text/html;charset=utf-8");
        multipart.addBodyPart(contentPart);
        if (files.length != 0) {
            for (File attachment : files) {
                BodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.setDataHandler(new DataHandler(new FileDataSource(attachment)));
                //避免中文乱码的处理
                attachmentPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                multipart.addBodyPart(attachmentPart);
            }
        }
        message.setContent(multipart);
        message.saveChanges();
        //用流传送
        Transport transport = session.getTransport();
        transport.connect(FROM, PASSWORD);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

        return to;
    }


    @Test
    public void send()
        throws MessagingException, GeneralSecurityException, UnsupportedEncodingException {
//        String[] filePaths = {"C:\\Users\\Administrator\\Desktop\\冰雪大世界.jpg"};
//        File[] files = new File[filePaths.length];
//        Assert.assertTrue("图片不存在", file);
        File[] files = Stream.of(new File("C:\\Users\\Administrator\\Desktop\\冰雪大世界.jpg"))
            .toArray(File[]::new); // 创建一个包含特定File对象的数组
        String sendSuccessToList = sendHtmlMailWithFiles("测试邮件图片", "this is 测试内容", files);
        System.out.println("sendSuccessToList = " + sendSuccessToList);
    }


    /**
     * 检查是否是QQ邮箱
     */
    private void checkQQMail() {
        if (FROM.contains("qq.com")) {
            isSSLAuth = true;
        }
    }

}


